import React, { Fragment, useState, useEffect } from 'react'

import { PageHeaderWrapper } from '@ant-design/pro-layout'
import {
  Card,
  Row,
  Col,
  Button,
  Table,
  Pagination,
  Select,
  DatePicker
} from 'antd'

import { getChannelCount, getCountChannelList } from '@/services/channel'
import moment from 'moment'
import channelStyles from './index.less'
import { message } from 'antd'

const { Option } = Select
const { RangePicker } = DatePicker

const ChannelCount = () => {
  const columns = [
    {
      title: 'UV(去重)',
      dataIndex: 'uv',
      align: 'center'
    },
    {
      title: '授权手机号',
      dataIndex: 'authorizations',
      align: 'center'
    },
    {
      title: '申请订单数',
      dataIndex: 'apply',
      align: 'center'
    },
    {
      title: '租用中',
      dataIndex: 'underLease',
      align: 'center'
    },
    {
      title: '日期',
      dataIndex: 'createTime',
      align: 'center'
    }
  ]

  const [pageInfo, setPageInfo] = useState({
    channelCode: '',
    pageNumber: 1,
    pageSize: 10,
    begin: moment().day(moment().day() - 7),
    end: moment()
    // begin: '',
    // end: ''
  })

  const [channelList, setChannelList] = useState([])
  const [statistics, setStatistics] = useState([])
  const [total, setTotal] = useState(0)
  const [selectedValue, setSelectedVal] = useState('')

  const loadList = async () => {
    try {
      const params = { ...pageInfo }
      params.begin = moment(params.begin).format('YYYY-MM-DD')
      params.end = moment(params.end).format('YYYY-MM-DD')
      const { data } = await getChannelCount(params)
      setStatistics(data.records)
      setTotal(data.total)
    } catch (error) {
      message.error(error.message)
    }
  }

  const onSearchBtn = () => {
    setPageInfo({ ...pageInfo, pageNumber: 1, pageSize: 10 })
  }

  const onRangePicker = ([begin, end]) => {
    // const day = moment(end).diff(begin, 'day')
    // if (day > 7) {
    //   return message.error('选择时间范围不能超过七天')
    // }

    setPageInfo({
      ...pageInfo,
      begin,
      end
    })
    // setSelectedVal('')
  }

  const onReset = () => {
    setPageInfo({
      ...pageInfo,
      pageNumber: 1,
      pageSize: 10,
      channelCode: '',
      begin: moment().day(moment().day() - 7),
      end: moment()
    })
    setSelectedVal('')
  }

  const loadChannelList = async () => {
    try {
      const { data } = await getCountChannelList()
      setChannelList(data)
      // if (data.length === 1) {
      //   const { channelCode } = data[0]
      //   setPageInfo({ ...pageInfo, channelCode })
      //   setSelectedVal(channelCode)
      // } else {
      //   loadList()
      // }
      // loadList()
    } catch (error) {
      message.error(error.message)
    }
  }

  useEffect(() => {
    loadChannelList()
  }, [])

  useEffect(() => {
    // if (pageInfo.channelCode || channelList.length > 1) {
    //   loadList()
    // }
    loadList()
  }, [pageInfo])

  const onPageChange = pageNumber => {
    setPageInfo({ ...pageInfo, pageNumber })
  }

  const onSizeChange = (current, pageSize) => {
    setPageInfo({ ...pageInfo, pageSize })
  }

  const handleChange = channelCode => {
    setPageInfo({ ...pageInfo, channelCode })
    setSelectedVal(channelCode)
  }

  return (
    <Fragment>
      <PageHeaderWrapper title="渠道管理">
        <Card>
          <Row gutter={16}>
            <Col span={24}>
              <Row type="flex">
                <Col span={12}>
                  <Row type="flex">
                    <Col span={8}>
                      <div>
                        <span>渠道：</span>
                        <Select
                          showSearch
                          optionFilterProp="children"
                          filterOption={(input, option) =>
                            option.props.children
                              .toLowerCase()
                              .indexOf(input.toLowerCase()) >= 0
                          }
                          style={{ width: 120 }}
                          defaultValue={selectedValue}
                          value={selectedValue}
                          onChange={handleChange}
                        >
                          {/* {channelList.length !== 1 && (
                            <Option value="">全部</Option>
                          )} */}
                          <Option value="" key="">
                            全部
                          </Option>
                          {channelList.map(channel => {
                            return (
                              <Option key={channel} value={channel.channelCode}>
                                {channel.channelName}
                              </Option>
                            )
                          })}
                        </Select>
                      </div>
                    </Col>
                    <Col span={16}>
                      <div>
                        <span>日期：</span>
                        <RangePicker
                          onChange={onRangePicker}
                          style={{ width: 240 }}
                          value={[pageInfo.begin, pageInfo.end]}
                          defaultValue={[
                            moment(pageInfo.begin, 'YYYY/MM/DD'),
                            moment(pageInfo.end, 'YYYY/MM/DD')
                          ]}
                          format="YYYY/MM/DD"
                        />
                      </div>
                    </Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row type="flex" justify="end">
                    <Button type="primary" onClick={onSearchBtn}>
                      查询
                    </Button>
                    <Button type="info" onClick={onReset}>
                      重置
                    </Button>
                  </Row>
                </Col>
              </Row>
            </Col>
          </Row>

          <Table
            className={channelStyles.table}
            bordered
            dataSource={statistics}
            columns={columns}
            pagination={false}
            rowKey="createTime"
          />

          <Pagination
            style={{ marginTop: 20, textAlign: 'right' }}
            showTotal={t => `共有 ${t} 条`}
            total={total}
            current={pageInfo.pageNumber}
            pageSize={pageInfo.pageSize}
            defaultPageSize={10}
            pageSizeOptions={['10', '20', '30', '50']}
            showSizeChanger
            showQuickJumper
            onChange={onPageChange}
            onShowSizeChange={onSizeChange}
          />
        </Card>
      </PageHeaderWrapper>
    </Fragment>
  )
}

export default ChannelCount
